<script>
import { Plus } from '@element-plus/icons-vue'
import { addBanner } from '@/api/banner'
import { ElMessage } from 'element-plus'
export default {
  name: 'addbanner',
  data() {
    return {
      imageUrl: '',
      formData: {
        alt: '',
        link: '',
        img: ''
      }
    }
  },
  components: {
    Plus
  },
  methods: {
    httpRequest(options) {
      // options.file 为我们选中的文件

      // console.log(options.file)

      //URL.createObjectURL 根据文件生成一个 url 地址,改地址用于展示的临时地址
      // this.imageUrl = URL.createObjectURL(options.file)

      // 1.将图片转换成 base64

      //创建一个文件的加载器(用来读取文件用的)
      let reader = new FileReader()
      //指定加载指定的文件
      reader.readAsDataURL(options.file)

      //监听加载完成之后的一个回调函数
      reader.onload = () => {
        // console.log(reader.result)
        this.imageUrl = reader.result
        this.formData.img = reader.result
      }

      // 2. 将图片传递给服务器
    },

    //添加按钮的点击事件
    addBanner() {
      // console.log(this.formData)
      if (this.formData === '' || this.formData.alt === '' || this.formData.img === '' || this.formData.link === '') {
        ElMessage.error('信息不完善')
        return
      } else {
        addBanner(this.formData).then(res => {
          // console.log(res)
          if (res.code === '200') {
            ElMessage.success('轮播图添加成功')

            //提交成功后进入到轮播图列表页面
            this.$router.push('/banner/bannerlist')
          }
        })
      }
    }
  }
}
</script>
<template>
  <div>
    <h1>添加轮播图</h1>

    <el-form-item label="请输入 alt">
      <el-input placeholder="请输入 alt" v-model="formData.alt" />
    </el-form-item>
    <el-form-item label="请输入 link">
      <el-input placeholder="请输入 link" v-model="formData.link" />
    </el-form-item>
    <el-form-item label="请选择图片">
      <el-upload class="avatar-uploader" :http-request="httpRequest">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>

    <el-button @click="addBanner">添加</el-button>

  </div>
</template>


<style lang="scss" scope>
.avatar-uploader .el-upload {
  border: 3px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>